package com.inspur.edp.rule.dsl.core.function.list.getter;

import com.inspur.edp.rule.dsl.core.function.list.IGetFieldValue;
import lombok.Data;

import java.lang.reflect.Field;

@Data
public class DirectGetter implements IGetFieldValue {

    private Field field;

    public DirectGetter(Class cls, String fieldName) {
        try {
            this.field = cls.getDeclaredField(fieldName);
        } catch (Throwable throwable) {
            throw new IllegalArgumentException("get field info occur error.", throwable);
        }
    }

    public Object getFieldValue(Object object) {
        try {
            this.field.setAccessible(true);
            Object value = this.field.get(object);
            return value;
        } catch (Throwable throwable) {
            throw new IllegalArgumentException("get field value occur error.", throwable);
        }
    }

    @Override
    public String getString(Object object) {
        return (String) this.getFieldValue(object);
    }

    @Override
    public Number getNumber(Object object) {
        return (Number) this.getFieldValue(object);
    }
}
